package com.cellngine.hub;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import com.cellngine.Constants;
import com.cellngine.cellngine;

public class WebServer implements Runnable
{
	private ServerSocket	server;
	private int				port;
	private Thread			thread;
	
	public WebServer(final int port)
	{
		//Generate the MIME types so we can determine the content type later on.
		new MIME();
		
		//Initialize the server and spawn a new thread to host it in.
		try
		{
			this.server = new ServerSocket(port);
		}
		catch (final IOException e)
		{
			cellngine.log(e, Constants.log_type.error);
		}
		
		this.thread = new Thread(this);
		this.thread.start();
	}
	
	@Override
	public void run()
	{
		while (true)
		{
			try
			{
				//Start accepting connections; when one is received create a new thread to handle it.
				final Socket s = this.server.accept();
				
				final Thread t = new Thread(new WebServerHandler(s));
				t.run();
			}
			catch (final SocketException e)
			{
				//The server has been shut down, so we don't need to report anything.
				return;
			}
			catch (final IOException e)
			{
				cellngine.log(e, Constants.log_type.error);
			}
			
			//Make sure other threads (i.e., client processing threads and the main thread) can still function.
			Thread.yield();
		}
	}
	
	public void close()
	{
		try
		{
			this.server.close();
		}
		catch (final IOException e)
		{
			cellngine.log(e, Constants.log_type.error);
		}
	}
	
	public int getPort()
	{
		return this.port;
	}
}